<template>
  <div>

    <!--  弹出方向改为全局的用户可配置 vue store 中  -->
    <!--  最大最小百分比设置 -->
    <!--        -->
    <el-drawer
      :before-close="handleClose"
      :show-close="false"
      :visible.sync="drawerVisible"
      :withHeader="false"
      :wrapperClosable="false"
      ref="drawer"
      size="60%"
    >

      <!--   必须要做成滚动加载的table,   -->
      <!--      title="产品物料列表"    -->
      <!--     form  > row > col > formItem > input ...     -->
      <el-card style="margin: 0 10px">
        <div slot="header" style="display: flex;justify-content: space-between;align-items: center">
          <span>全部产品物料列表</span>
          <AButton
            :type="dataHasChange ? 'success':'primary' "
            @click="$refs.drawer.closeDrawer()">
            关闭{{dataHasChange ? '并保存':''}}物料信息列表
            <el-divider direction="vertical"></el-divider>
            <i class="el-icon-circle-close"></i>
          </AButton>

          <!--              <transition name="el-fade-in-linear">-->
          <!--                <el-button-->
          <!--                  @click="ModifyProductMaterial"-->
          <!--                  type="success" >-->
          <!--                  保存物料-->
          <!--                </el-button>-->
          <!--              </transition>-->
        </div>

        <!--        <div>-->
        <!--          <el-tag/>-->
        <!--        </div>-->

        <el-alert
          :closable="false"
          show-icon
          title="蓝色标识的为已经添加的,白色表示未添加"
          type="success"
        />

        <el-checkbox-group
          size="mini"
          v-model="proxyCheckedItemIds">
          <!--                   v-loading="listLoading"   -->
          <!--          <transition appear name="el-zoom-in-center">-->
          <azure-dynamic-table
            :column-des-objs="columnDesObjs"
            :data="tableData"
            :showSeq="true"
            class="list-table"
            empty-text="该工艺暂无配置物料 🎉🎉🎉🎉🎉"
            height="60vh"
          >
            <template #tableHead>
              <el-input
                @keyup.native.enter="resetSearch"
                clearable
                placeholder="请输入产品名|产品编码搜索"
                size="small"
                style="width: 290px"
                v-model="searchFormData.inkey">
                <el-button @click="resetSearch"
                           icon="el-icon-search"
                           slot="append">
                </el-button>
              </el-input>
            </template>
            <template slot="operator3" slot-scope="{scope:{row,$index}}">
              <el-checkbox-button style="width: 90px;" :label="row.MaterialItemID">
                {{`${checkedItemIds.includes(row.MaterialItemID) ? '已添加📌':'添加物料📍'}`}}
              </el-checkbox-button>
            </template>

            <!--            <infinite-loading-->
            <!--              :identifier="infiniteId"-->
            <!--              @infinite="infinite"-->
            <!--              force-use-infinite-wrapper=".el-table__body-wrapper"-->
            <!--              slot="azure"-->
            <!--              style="margin: 10px 0;">-->
            <!--              <div class="no-more" slot="no-more">-->
            <!--                {{searchFormData.page >=10 ? '看了这么多页了休息一下吧😎😎.....' : '没有更多了😜🎶🤣🎉🎁..... (～￣▽￣)～'}}-->
            <!--              </div>-->
            <!--              <div class="no-more" slot="no-results">-->
            <!--                暂无结果🤞🐱‍👤🐱‍💻🐱‍🐉🐱 Ծ‸Ծ-->
            <!--              </div>-->
            <!--              <div class="no-more" slot="error">-->
            <!--                出错了 (╯‵□′)╯︵┻━┻😁😒🎁😢🤞🐱‍👤🐱‍💻🐱‍🐉🐱‍👓🐱‍🚀-->
            <!--              </div>-->
            <!--            </infinite-loading>-->

          </azure-dynamic-table>
          <!--          </transition>-->
        </el-checkbox-group>

      </el-card>

    </el-drawer>
  </div>
</template>

<script>
  import InfiniteLoading from 'vue-infinite-loading'
  import AzureDynamicTable from '@/components/ATheFridayClub/mDynamicTable/AzureDynamicTable'
  // import { columnDesObjs } from '@/views/baseproduct/components/halfComponent/materialUtil'
  import { MaterialItemGetAllPage, ModifyProductMaterial, QueryProductLinkTechRoute } from '@/api/productInformation'
  import { ERR_OK } from '@/utils/commons'
  import AButton from '@/components/ATheFridayClub/AButton'
  //  materialCols
  /**

   */
  const columnDesObjs = Array.of(
    { key: 'Name', label: '材料名' }, //     "铜板250g爱丽丝细绒(750X585mm)"
    { key: 'Code', label: '材料编码', tag: true, width: 150 }, //     "B2No1001"
    { key: 'Unit', label: '单位', tag: true, isDefaultShowDynamicColumn: false }, //     ""
    { key: 'CostPrice', label: '价格', width: 150, isDefaultShowDynamicColumn: false },  //     0
    { key: 'Weight', label: '重量', width: 150, isDefaultShowDynamicColumn: false },  //     0.13
    { key: 'MaterialType', label: '材料类型', isDefaultShowDynamicColumn: false }, //     1
    { key: 'MaterialClassId', label: '材料类型ID', isDefaultShowDynamicColumn: false },  //     1
    // { key: 'MaterialItemCurrencyId', label: '' }, //     null
    { key: 'MaterialItemID', label: '材料ID', isDefaultShowDynamicColumn: false }, //     2
    { key: 'MaxCapacity', label: '最大容量', isDefaultShowDynamicColumn: false },  //     0
    { key: 'Remark', label: '详情描述', isDefaultShowDynamicColumn: false }, //     null
    // { key: 'SizeDetailId', label: '' }, //     4685
    { key: 'Specification', label: '说明', isDefaultShowDynamicColumn: false }  //     " 750X585mm"
  )

  export default {
    name: 'AddMaterial2TechRouteDrawer',
    components: { AButton, AzureDynamicTable, InfiniteLoading },
    props: {
      dataHasChange: {
        type: Boolean
      },
      routeHasMaterial: {
        type: Array,
        default: () => ([])
      },

      //    当前选中的材料ids
      checkedItemIds: {
        type: Array,
        default: () => ([])
      },
      backMaterialItemID: {}
    },
    inject: ['deleteMaterial', 'ModifyProductMaterial'],
    computed: {
      proxyCheckedItemIds: {
        get() {
          return this.checkedItemIds
        },
        set(checkedIds) {
          this.$emit('update:dataHasChange', true)
          this.$emit('checkedItemIdsChange',
            checkedIds,
            this.tableData.filter(v => checkedIds.includes(v.MaterialItemID))
          )

          //  通过计算获取到最后的结果table,不行,因为缺少创建的逻辑
        }
      }
    },
    data() {
      return {

        drawerVisible: false,
        columnDesObjs: Array.of(...columnDesObjs,
          // { label: '选择', key: 'check' }
          { label: '操作', key: 'operator3', width: 130 }
        ),
        listLoading: false,
        tableData: Array.of(),

        //  分页相关

        searchFormData: {
          page: 1,  //  0页开始.....🤣🤣🤣🤣🤣
          limit: 100,
          inkey: ''
        },

        total: 0,
        infiniteId: +new Date(),

        tableKey: +new Date()
      }
    },
    created() {
      this.MaterialItemGetAllPage()
    },
    mounted() {
      console.log('infiniteId')

      this.infiniteId++
    },
    methods: {

      resetSearch() {
        // CheckList: null
        // CurrentPage: 0
        // TotalNum: 1
        // TotalPageCount: 1
        this.tableData = Array.of()
        this.searchFormData.page = 1
        // this.total = 0
        this.infiniteId++

        this.MaterialItemGetAllPage()
      },
      infinite($state) {
        console.log('laod data ')

        this.MaterialItemGetAllPage({ $state })
      },
      async MaterialItemGetAllPage({ $state } = {}) {
        try {
          const { searchFormData: { page, limit: pagesize, inkey } } = this
          console.log(this.searchFormData)
          // const { ProductId } = this.$route.query
          const { Code, Result } = await MaterialItemGetAllPage({
            inkey,  //  忽略的参数
            page,
            pagesize
          })
          if (Code === ERR_OK) {
            //  CurrentPage: this.searchFormData.page,
            const { TotalNum } = Result
            this.total = TotalNum
            //  每次查询的数据进行加工,如果加载的新数据在已有的中存在
            //  就把已有的数据的数量和某些属性添加进去
            this.tableData.push(...Result['Items'])
            // $state.loaded()
            if (this.searchFormData.page * this.searchFormData.limit >= TotalNum) {
              // $state.complete()
            } else {
              this.searchFormData.page++
            }
          } else {
            // $state.error()
          }
        } catch (e) {
          console.log(e)
          // $state.error()
        }
      },

      //  关闭前提示是否保存
      handleClose(done) {
        this.dataHasChange ?
          this.$alert('你的编辑会被自动保存并生效', '你已经当前关闭了窗口', {
            confirmButtonText: '我知道了',
            callback: async action => {
              await this.deleteMaterial({ ids: this.backMaterialItemID, showMsg: false })  //  把原有的全部删除,再重新添加
              await this.ModifyProductMaterial({ dataList: this.routeHasMaterial })
              done()
            }
          }) : (async() => {
            done()
          })()

        // this.$confirm('确认关闭并保存,点击取消放弃保存？').then(async _ => {
        //   // console.log(this.backMaterialItemID)
        //   done()
        // }).catch(err => {
        //   console.log(err)
        //   if (err === 'cancel') {
        //     done()
        //   }
        // })
      },

      //  提交按钮
      handleSubmit() {
        //  现在的问题就是去重复
      },

      // openedDrawer() {
      //   // await this.$nextTick()
      //   this.infiniteId += 1
      //   this.tableKey++
      // },

      async handleAddHalfProduct() {
        this.drawerVisible = true
      }

    }

  }
</script>


<style lang="scss" scoped>
  @import "~@/styles/index.scss";

  .list-table {
    @include tableScrollBar()
  }

</style>
